from binn_list import BinnList
from binn_map import BinnMap
from binn_obj import BinnObj
from datatypes import *
def decode_list(binno):
    it = binno.begin()
    pylist = []
    while it.next():
        if it.get_type() == BINN_OBJECT:
            childo = BinnObj(it.get_value())
            child = decode_object(childo)
            pylist.append(child)
        elif it.get_type() == BINN_MAP:
            childm = BinnList(it.get_value())
            child = decode_map(childm)
            pylist.append(child)
        elif it.get_type() == BINN_LIST:
            childl = BinnList(it.get_value())
            child = decode_list(childl)
            pylist.append(child)
        else:
            child = it.get_value()
            pylist.append(child)
    return pylist

def decode_obj(binno):
    it = binno.begin()
    pydict = dict()
    while it.next():
        key = it.get_key()
        if it.get_type() == BINN_OBJECT:
            childo = BinnObj(it.get_value())
            child = decode_object(childo)
            pydict[key] = child
        elif it.get_type() == BINN_MAP:
            childm = BinnList(it.get_value())
            child = decode_map(childm)
            pydict[key] = child
        elif it.get_type() == BINN_LIST:
            childl = BinnList(it.get_value())
            child = decode_list(childl)
            pydict[key] = child
        else:
            child = it.get_value()
            pydict[key] = child
    return pydict

def decode_map(binno):
    it = binno.begin()
    pydict = dict()
    while it.next():
        key = it.get_iden()
        if it.get_type() == BINN_OBJECT:
            childo = BinnObj(it.get_value())
            child = decode_object(childo)
            pydict[key] = child
        elif it.get_type() == BINN_MAP:
            childm = BinnList(it.get_value())
            child = decode_map(childm)
            pydict[key] = child
        elif it.get_type() == BINN_LIST:
            childl = BinnList(it.get_value())
            child = decode_list(childl)
            pydict[key] = child
        else:
            child = it.get_value()
            pydict[key] = child
    return pydict

def decode(binno):
    if isinstance(binno, BinnList):
        return decode_list(binno)
    elif isinstance(binno, BinnObj):
        return decode_obj(binno)
    elif isinstance(binno, BinnMap):
        return decode_map(binno)
    else:
        raise TypeError('')
